package reesoft.certificate.entity;

import reesoft.common.entity.BaseRequest;

import java.util.*;

/**
 * Created by reesoft on 2017-08-30
 */
public class SignRequest extends BaseRequest
{
    // 签名算法
    private String signType;

    // 数字签名
    private String signature;

    public String getSignType()
    {
        return signType;
    }

    public void setSignType(String signType)
    {
        this.signType = signType;
    }

    public String getSignature()
    {
        return signature;
    }

    public void setSignature(String signature)
    {
        this.signature = signature;
    }

    /**
     * 把请求对象所有成员变量排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @return 拼接后字符串
     */
    public String generateSignData()
    {
        return generateSignData(toParameterMap());
    }

    /**
     * 把参数集合所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @param parameters 需要排序并参与字符拼接的参数集合
     * @return 拼接后字符串
     */
    private static String generateSignData(Map<String, String> parameters)
    {
        parameters = filterSignParameters(parameters);

        List<String> keys = new ArrayList<>(parameters.keySet());
        Collections.sort(keys);

        StringBuilder result = new StringBuilder();

        for (String key : keys)
        {
            result.append(key).append("=").append(parameters.get(key)).append("&");
        }

        if (result.length() > 0)
        {
            result.delete(result.length() - 1, result.length());
        }

        return result.toString();
    }

    /**
     * 除去参数集合中的空指针值和签名参数
     *
     * @param parameters 参数集合
     * @return 去掉空指针值与签名参数后的参数集合
     */
    private static Map<String, String> filterSignParameters(Map<String, String> parameters)
    {
        Map<String, String> result = new HashMap<>();

        if (parameters == null || parameters.isEmpty())
        {
            return result;
        }

        for (String key : parameters.keySet())
        {
            String value = parameters.get(key);

            if (value != null
                    && !key.equalsIgnoreCase("signType")
                    && !key.equalsIgnoreCase("signature"))
            {
                result.put(key, value);
            }
        }

        return result;
    }
}
